package com.lagou.edu.mvcframework.interceptor;

import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.pojo.Handler;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Logger;

public class SecurityInterceptor  implements  Interceptor{


    /**
     * 返回值代表是否放行
     * 完成权限校验
     * @param request
     * @param response
     * @param handler
     * @return
     */
    public boolean  preHandler(HttpServletRequest request, HttpServletResponse response,Object handler){
        if(handler instanceof Handler){

            Handler handlerObject = (Handler) handler;
            Security annotation = handlerObject.getMethod().getAnnotation(Security.class);
            if(annotation==null) {
              return  true;
            }

            //有访问授权的值列表
            List<String> valusList = Arrays.asList(annotation.auThValue());
            Set<String> authValue = new HashSet<String>(valusList);
            //授权属性名
            String auThField= annotation.auThField();

            Map<String, String[]> parameterMap = request.getParameterMap();
            Map<String,String> paramteerValueMap = new HashMap<>();
            for(Map.Entry<String,String[]> param: parameterMap.entrySet()) {
                // name=1&name=2   name [1,2]
                String value = StringUtils.join(param.getValue(), ",");  // 如同 1,2
                paramteerValueMap.put(param.getKey(),value);
            }
                System.out.println("parameterMap="+parameterMap.toString());
            String[] paramValue = parameterMap.get(auThField);
            if(paramValue!=null && paramValue.length>0){
                for (String s : paramValue) {
                    if(authValue.contains(s)){
                        System.out.println("授权通过，授权value："+authValue.toString()+"，授权参数值为："+s);
                        return true;
                    }
                }
            }
            if(paramValue==null) {
                System.out.println("授权不不通过，授权value：" + authValue.toString() + "，因为授权参数值为：" + paramteerValueMap.get(auThField));
            }else{
                System.out.println("授权不不通过，授权value：" + authValue.toString() + "，因为授权参数值为：" + paramteerValueMap.get(auThField));
            }
            return false;
        }
        return true;
    }


}
